package edu.friday.controller;

import edu.friday.common.base.BaseController;
import edu.friday.common.constant.UserConstants;
import edu.friday.common.result.RestResult;
import edu.friday.common.security.LoginUser;
import edu.friday.common.security.service.MyTokenService;
import edu.friday.model.SysMenu;
import edu.friday.model.vo.SysMenuVO;
import edu.friday.service.SysMenuService;
import edu.friday.service.SysUserService;
import edu.friday.utils.BeanUtils;
import edu.friday.utils.http.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {
    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private MyTokenService myTokenService;

    @GetMapping("/list")
    public RestResult list(SysMenuVO sysMenuvo) {

        Long userId=getUserId();

        List<SysMenu> sysMenus =sysMenuService.selectMenuList(sysMenuvo,userId);
        return RestResult.success(sysMenus);
    }

    private Long getUserId() {
        LoginUser loginUser = myTokenService.getLoginUser(ServletUtils.getRequest());
        return loginUser.getUser().getId();
    }



    @PostMapping
    public RestResult add(@RequestBody SysMenuVO sysMenuVO) {
        SysMenu sysMenu = new SysMenu();
        BeanUtils.copyProperties(sysMenuVO, sysMenu);
        if(UserConstants.NOT_UNIQUE.equals(sysMenuService.checkMenuNameUnique(sysMenu))){
            return RestResult.error("新增菜单"+sysMenu.getMenuName()+"失败，名称已存在");
        }
        sysMenu.setCreateBy("system");
        return toAjax(sysMenuService.insertMenu(sysMenu));
    }

    @PutMapping
    public RestResult edit(@RequestBody SysMenuVO sysMenuVO) {
        SysMenu sysMenu = new SysMenu();
        BeanUtils.copyProperties(sysMenuVO, sysMenu);
        if(UserConstants.NOT_UNIQUE.equals(sysMenuService.checkMenuNameUnique(sysMenu))){
            return RestResult.error("修改菜单"+sysMenu.getMenuName()+"失败，名称已存在");
        }
        sysMenu.setCreateBy("system");
        return toAjax(sysMenuService.updateMenu(sysMenu));
    }

    @DeleteMapping("{menuId}")
    public RestResult delete(@PathVariable Long menuId) {
        if(sysMenuService.hasChildByMenuId(menuId)){
            return RestResult.error("存在子菜单，不允许删除");
        }
        if (sysMenuService.checkMenuExistRole(menuId)){
            return RestResult.error("菜单已分配，不允许删除");
        }
        return toAjax(sysMenuService.deleteMenuById(menuId));
    }
}
